<?php

/**
 * 公众号第三方平台API
 * @author lovebing <lovebing365@126.com> Created on 2015-4-12
 */
class WechatComponent {

    const API_BASE_URL = 'https://api.weixin.qq.com/cgi-bin/component/';

    protected $clientAppid = '';
    protected $appid;
    protected $appsecret;
    protected $verifyTicket;
    protected $componentAccessToken = '';
    protected $errmsg = '';
    protected $errcode = 0;

    /**
     * 
     * @param array $conf
     */
    public function __construct(array $conf) {
        if (isset($conf['clientAppid'])) {
            $this->clientAppid = $conf['clientAppid'];
        }
        if (isset($conf['appid'])) {
            $this->appid = $conf['appid'];
        }
        if (isset($conf['appsecret'])) {
            $this->appsecret = $conf['appsecret'];
        }
        if (isset($conf['verifyTicket'])) {
            $this->setVerifyTicket($conf['verifyTicket']);
        }
    }

    public function setVerifyTicket($verifyTicket) {
        $this->verifyTicket = $verifyTicket;
    }

    /**
     * 
     * @param type $code
     * @return type
     */
    private function getErrorCodeName($code) {
        $name = '';
        switch ($code) {
            case -100:
                $name = '连接失败';
            default :
                $name = $code;
        }
        return $name;
        ;
    }

    public function getErrorCode() {
        return $this->errcode;
    }

    public function getErrorMessage() {
        return $this->errmsg;
    }

    /**
     * 
     * @param type $token
     * @return boolean
     */
    public static function checkSignature($token) {
        $signature = filter_input(INPUT_GET, 'signature');
        $timestamp = filter_input(INPUT_GET, 'timestamp');
        $nonce = filter_input(INPUT_GET, 'nonce');

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = sha1(implode($tmpArr));

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     * @param string $res
     * @return boolean
     */
    private function parseResult($res) {
        $data = json_decode($res, true);
        if (!is_array($data)) {
            $this->errcode = -100;
            $this->errmsg = $this->getErrorCodeName($this->errcode);
            return false;
        }
        $this->errcode = isset($data['errcode']) ? $data['errcode'] : 0;
        if ($this->errcode != 0) {
            $this->errmsg = isset($data['errmsg']) ? $data['errmsg'] : $this->getErrorCodeName($this->errcode);
        } else {
            $this->errmsg = '';
        }
        return $data;
    }

    /**
     * 获取第三方平台access_token
     */
    public function componentToken() {
        $url = self::API_BASE_URL . 'api_component_token';
        $params = array(
            'component_appid' => $this->appid,
            'component_appsecret' => $this->appsecret,
            'component_verify_ticket' => $this->verifyTicket
        );

        $http = HTTPClient::getInstance();
        $res = $http->postText($url, json_encode($params));

        $data = $this->parseResult($res);
        if ($this->errcode) {
            return false;
        }

        $this->componentAccessToken = $data['component_access_token'];
        return $data;
    }

    public function setComponentAccessToken($token) {
        $this->componentAccessToken = $token;
    }
    
    public function getComponentAccessToken() {
        return $this->componentAccessToken;
    }

    /**
     * 获取预授权码
     * @return type
     */
    public function createPreauthcode() {
        $url = self::API_BASE_URL . 'api_create_preauthcode?component_access_token=' . $this->componentAccessToken;
        $params = array(
            'component_appid' => $this->appid
        );

        $http = HTTPClient::getInstance();
        $res = $http->postText($url, json_encode($params));
        $data = $this->parseResult($res);

        if ($this->errcode) {
            return false;
        }
        return $data['pre_auth_code'];
    }

    /**
     * 
     * @param type $authorizationCode
     * @return boolean
     */
    public function queryAuth($authorizationCode) {
        $url = self::API_BASE_URL . 'api_query_auth?component_access_token=' . $this->componentAccessToken;
        $params = array(
            'component_appid' => $this->appid,
            'authorization_code' => $authorizationCode
        );

        $http = HTTPClient::getInstance();
        $res = $http->postText($url, json_encode($params));
        $data = $this->parseResult($res);

        if ($this->errcode) {
            return false;
        }
        if(!isset($data['authorization_info'])) {
            return false;
        }
        return $data['authorization_info'];
    }

    /**
     * 获取授权url
     * @param type $redirectUri
     * @return type
     */
    public function getComponentLoginPageUrl($redirectUri) {
        $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage';

        $params = array(
            'component_appid' => $this->appid,
            'pre_auth_code' => $this->createPreauthcode(),
            'redirect_uri' => $redirectUri
        );

        return $url . '?' . http_build_query($params);
    }

}
